var ISS = {};


TEMPLATE = {};
ISS.DOMAIN = {};

ISS.EVENT = {
   bindEvent: function (selector, eventName, func) {
      $(selector).bind(eventName, func);
   },

   detachEvent: function (selector, eventName, func) {
      $(selector).unbind(eventName, func);
   },

   delegate: function (selector, childSelector, eventName, func) {
      $(selector).delegate(childSelector, eventName, func);
   }
};

ISS.DOM = {
   loadJsCssFile: function (filename, filetype) {
      if (filetype=="js"){ //if filename is a external JavaScript file
         var fileref = document.createElement('script')
         fileref.setAttribute("type","text/javascript")
         fileref.setAttribute("src", filename)
      }
      else if (filetype=="css"){ //if filename is an external CSS file
         var fileref = document.createElement("link")
         fileref.setAttribute("rel", "stylesheet")
         fileref.setAttribute("type", "text/css")
         fileref.setAttribute("href", filename)
      }
      if (typeof fileref!="undefined") {
         document.getElementsByTagName("footer")[0].appendChild(fileref)
      }
   },
   load: function (selector, file) {
      $(selector).load(file);
   },
   append: function (selector, tag) {
      $(selector).append(tag);
   },
   removeClass: function (selector, classname) {
      $(selector).removeClass(classname);
   },
   addClass: function (selector, classname) {
      $(selector).addClass(classname);
   },
   css: function (selector, val) {
      $(selector).css(val);
   },
   html: function (selector, content) {
      $(selector).html(content);
   },
   setAtt: function (selector, att, value) {
      $(selector).attr(att, value);
   },
   getAtt: function (selector, att) {
      return $(selector).attr(att);
   },
   removeAttr: function (selector, func) {
      $(selector).removeAttr(func);
   },
   remove: function (selector, func) {
      $(selector).remove(func);
   },
   setVal: function (selector, value) {
      $(selector).val(value);
   },
   getVal: function (selector) {
      return $(selector).val();
   },
   hide: function (selector) {
      $(selector).hide();
   },
   show: function (selector) {
      $(selector).show();
   },
   att: function (selector, func) {
      $(selector).attr(func);
   },
    before: function (selector, content) {
      $(selector).before(content);
    },
    after: function (selector, content) {
        $(selector).after(content);
    },
   text: function (selector, text) {
      $(selector).text(text);
   },

   getText: function (selector) {
      return $(selector).text();
   },
   getData: function (selector ,att) {
      return $(selector).data( att);
   },

   forEach: function (selector, fn) {
      $(selector).each(fn);
   },

   paging: function (selector) {
      $(selector).simplePagination({
         first_content: '&lt;&lt;',
         previous_content: '<',
         next_content: '>',
         last_content: '>>',
         items_per_page: 52
      });
   },

   pagingAdmin: function (selector) {
      $(selector).simplePagination({
         pagination_container: 'tbody',
         first_content: '&lt;&lt;',
         previous_content: '<',
         next_content: '>',
         last_content: '>>',
         items_per_page: 25
      });
   },
   scroll: function() {
      if (typeof catalog !== 'undefined' && typeof catalog.initialize !== 'undefined') {
         $(function() {
            catalog.initialize(window.store);
         });
      }
   }
};

ISS.EFFECTS = {
   slideDown: function(selector, speed, delay) {
      if(delay) {
         $(selector).delay(delay).slideDown(speed);
      }
      else {
         $(selector).slideDown(speed);
      }
   },

   slideUp: function(selector, speed, delay) {
      if(delay) {
         $(selector).delay(delay).slideUp(speed);
      }
      else {
         $(selector).slideUp(speed);
      }
   }
};

ISS.BACKEND = {
   request: function (func) {
      $.ajax(func);
   },

   downloadFile: function (uri, formId) {
      var form = $(formId);
      form.action = uri;
      form.submit();
   }
};

ISS.CONTROL = {
   dialog: function (selector, data) {
      $(selector).dialog(data, {
         close: function () {
            $(this).dialog('destroy');
         }});
   },
   lockScreen: function (sectionLock, classCss) {
      $('<div id="screenBlock"></div>').appendTo(sectionLock);
      $('#screenBlock').css( { opacity: 0, width: $(sectionLock).width(), height: $(sectionLock).height() } );
      $('#screenBlock').addClass('blockDiv');
      $('#screenBlock').animate({opacity: 0.7}, 200);
   },
   unLockScreen: function (sectionLock) {
      $('#screenBlock').animate({opacity: 0}, 200, function() {
         $('#screenBlock').remove();
      });
   }
};

ISS.STRING_UTIL = {
   format: function (template, config) {
      var s = template;
      for (var templateItem in config) {
         if (config.hasOwnProperty(templateItem)) {
            var regexp = new RegExp('\\{' + templateItem + '\\}', 'gi');
            s = s.replace(regexp, config[templateItem]);
         }
      }

      return s;
   },

   formatNumeral: function(num, f) {
      return numeral(num).format(f);
   },

   unFormatNumeral: function(s) {
      return numeral().unformat(s);
   }
};

ISS.VALIDATION = {
//ISS.VALIDATION.validatePattern(params.procedureCode, /^\d{1,4}$/)
   validatePattern: function (str, pattern) {
      var result = false;
      if (str && (str.search(pattern) > -1)) {
         result = true;
      }

      return result;
   },

   isNumber: function (str) {
      return (str - 0) == str && (''+str).replace(/^\s+|\s+$/g, "").length > 0;
   },

//   var validationResult = ISS.VALIDATION.validateEmail(patientEmail, true);
   validateEmail: function (email, optional) {
      var result = false;

      if (!email && optional) {
         result = true;
      }
      else if (!email && !optional) {
         result = false;
      }
      else {
         if (this.validatePattern(email, /^.+@.+(\.[A-Za-z]{2,4})$/)) {
            result = true;
         }
      }

      return result;
   },

//   ISS.VALIDATION.allowInput(e, /[0-9]|:/);
   allowInput: function (evt, pattern) {
      var theEvent = evt || window.event;
      var sKey = '';

      // Firefox: _event.charCode is 0 for functional key.
      // Chrome, Safari: the functional key is not caught in event keypress.
      if (theEvent.keyCode === 0) {
         sKey = '';
      }
      else {
         // prevent input that does not in allowance list to take effect
         var keyCode = theEvent.keyCode || theEvent.charCode;
         sKey = String.fromCharCode(keyCode);
         if (!this.validatePattern(sKey, pattern)) {
            theEvent.returnValue = false;
            if (theEvent.preventDefault) {
               theEvent.preventDefault();
            }

            // key is not allowed
            sKey = '';
         }
      }

      return sKey;
   },

   formatPhoneNumber: function (phoneNumber) {
      var result = false;

      if (!phoneNumber) {
         result = false;
      }
      // check format and assign new auto-formatted value
      else if (this.validatePattern(phoneNumber, /^\d{3}-\d{3}-\d{4}$/)) {
         result = true;
      }
      else if (this.validatePattern(phoneNumber, /^\d{10}$/)) {
         result = true;
      }
      else if (this.validatePattern(phoneNumber, /^\d{3}-\d{7}$/)) {
         result = true;
      }
      else if (this.validatePattern(phoneNumber, /^\d{6}-\d{4}$/)) {
         result = true;
      }

      return result;
   },

    compareDate: function(date1, date2, date3){
        var result = true;
        var date1, date2, date3;
        date1 = date1.split("-");
        date2 = date2.split("-");
        date3 = date3.split("-");
/*        if(date3[2] < date1[2] || date2[2] <date1[2] || date2[2] > date3[2]) {
            result = false;
        } else if (((date3[1] <= date2[1]) && (date3[2] <= date2[2])) || ((date3[1] >= date2[1]) && (date3[2] <= date2[2])) ) {
            result = false;
        } else if (((date3[1] <= date1[1]) && (date3[2] <= date1[2])) || ((date3[1] >= date1[1]) && (date3[2] <= date1[2])) ) {
            result = false;
        } else if (((date2[1] <= date1[1]) && (date2[2] <= date1[2])) || ((date2[1] >= date1[1]) && (date2[2] <= date1[2])) ) {
            result = false;
        } else if ( ((date3[0] <= date2[0]) && (date3[1] <= date2[1])) || ((date3[0] >= date2[0]) && (date3[1] <= date2[1])) ) {
            result = false;
        } else if ( ((date3[0] <= date1[0]) && (date3[1] <= date1[1])) || ((date3[0] >= date1[0]) && (date3[1] <= date1[1])) ) {
            result = false;
        } else if ( ((date2[0] <= date1[0]) && (date2[1] <= date1[1])) || ((date2[0] >= date1[0]) && (date2[1] <= date1[1])) ) {
            result = false;
        }*/

        return result;
    }
};

ISS.COOKIE = {
//   setCookie: function(name, value, expires, path, domain) {
//      var cookie = name + "=" + escape(value) + ";";
//
//      if (expires)
//      {
//         var d = new Date();
//         d.setTime(d.getTime() + (expires*24*60*60*1000));
//         var expires = "expires="+d.toUTCString();
//      }
//
//      if (path)
//         cookie += "path=" + path + ";";
//      if (domain)
//         cookie += "domain=" + domain + ";";
//
//      document.cookie = cookie;
//   },
    setCookie: function(name, value, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = name + '=' + value + ';' + expires + ';path=/';
    },

    getCookie: function(name) {
        var _name = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(_name) != -1) return c.substring(_name.length, c.length);
        }
        return "";
    }
};

ISS.SESSION = {
    setSession: function(key, value) {
        $.session.set(key, value);
    },

    getSession: function(key) {
        return $.session.get(key);
    },

    clearSession: function() {
        $.session.clear();
    },

    removeSession: function(key) {
        $.session.remove(key);
    }
};

ISS.WINDOW = {
//   ISS.WINDOW.location('/jsp/user/user-register.jsp');
   location: function(url) {
      window.location = ISS.SESSION.getSession('contextPath') + url;
   },

   currentLocation: function() {
      window.location = ISS.WINDOW.pathName();
   },

   pathName: function() {
      return window.location.pathname;
   }
} ;

ISS.DATE = {
   getFullDate: function(date) {
      var _day, _month, _year;
      _day = this.getDateString(date);
      _year = date.getFullYear();
      _month = date.getMonth() > 8 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1);
      return _day + '-' + _month + '-' + _year;
   },

    changeFormatDate: function(date){
        var date
        date = date.split("-");
        return date[2]+'-'+date[1]+'-'+date[0];
    },

   getMonthString: function(date) {
      var _month;
      _month = date.getMonth() > 8 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1);
      return _month;
   },

   getDateString: function(date) {
      var _date;
      _date = date.getDate() > 9 ? date.getDate() :'0' + date.getDate() ;
      return _date;
   },

   isBetWeen: function(fDateString, tDateString) {
      var _from = new Date(fDateString),
         _to = new Date (tDateString),
         now = new Date();

      if(now >= _from && now <= _to) {
         return true;
      }
      else {
         return false;
      }
   }
};

ISS.GRAPH = {
   chart: function(id) {
      Highcharts.data({
         csv: document.getElementById(id).innerHTML,
         itemDelimiter: '\t',
         parsed: function (columns) {

            var brands = {},
               brandsData = [],
               versions = {},
               drilldownSeries = [];

            // Parse percentage strings
            columns[1] = $.map(columns[1], function (value) {
               if (value.indexOf('%') === value.length - 1) {
                  value = parseFloat(value);
               }
               return value;
            });

            $.each(columns[0], function (i, name) {
               var brand,
                  version;

               if (i > 0) {

                  // Remove special edition notes
                  name = name.split(' -')[0];

                  // Split into brand and version
                  version = name.match(/([0-9]+[\.0-9x]*)/);
                  if (version) {
                     version = version[0];
                  }
                  brand = name.replace(version, '');

                  // Create the main data
                  if (!brands[brand]) {
                     brands[brand] = columns[1][i];
                  } else {
                     brands[brand] += columns[1][i];
                  }

                  // Create the version data
                  if (version !== null) {
                     if (!versions[brand]) {
                        versions[brand] = [];
                     }
                     versions[brand].push(['v' + version, columns[1][i]]);
                  }
               }

            });

            $.each(brands, function (name, y) {
               brandsData.push({
                  name: name,
                  y: y,
                  drilldown: versions[name] ? name : null
               });
            });
            $.each(versions, function (key, value) {
               drilldownSeries.push({
                  name: key,
                  id: key,
                  data: value
               });
            });

            // Create the chart
            $('#container').highcharts({
               chart: {
                  type: 'column'
               },
               title: {
                  text: 'Xu hướng mua hàng'
               },
               subtitle: {
                  text: ''
               },
               xAxis: {
                  type: 'category'
               },
               yAxis: {
                  title: {
                     text: 'Phần trăm'
                  }
               },
               legend: {
                  enabled: false
               },
               plotOptions: {
                  series: {
                     borderWidth: 0,
                     dataLabels: {
                        enabled: true,
                        format: '{point.y:.1f}%'
                     }
                  }
               },

               tooltip: {
                  headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
                  pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
               },

               series: [{
                  name: 'Brands',
                  colorByPoint: true,
                  data: brandsData
               }],
               drilldown: {
                  series: drilldownSeries
               }
            });
         }
      });
   }
}

ISS.TEMPLATE = {};
ISS.TEMPLATE.handleBar = {
   renderBySelector: function (selector, context) {
      var template = $(selector).html();
      var compiledTemplate = Handlebars.compile(template);
      var html = compiledTemplate(context);

      return html;
   },

   renderByString: function (template, context) {
      var compiledTemplate = Handlebars.compile(template);
      var html = compiledTemplate(context);

      return html;
   }
};

